package com.dalei.vds;

import java.lang.ref.WeakReference;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import com.dalei.vds.settings.ServerSettings;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SvrArgsSettingsActivity extends Activity {

	public static final int RESULT_ARGS_CHANGED = 0x00000002;

	private static final int MESSAGE_SHOW_DIALOG = 0x00000000;

	private static final int MESSAGE_DISMISS_DIALOG = 0x00000001;

	private static final int MESSAGE_SHOW_TOAST = 0x00000002;

	private static final int MESSAGE_ENABLE_SAVE = 0x00000003;

	private static final int MESSAGE_DISABLE_SAVE = 0x00000004;

	private EditText ipAddressPart1Edit;

	private EditText ipAddressPart2Edit;

	private EditText ipAddressPart3Edit;

	private EditText ipAddressPart4Edit;

	private EditText portEdit;

	private EditText timeoutEdit;

	private Button testBtn;

	private Button saveBtn;

	private Button cancelBtn;

	private ProgressDialog dialog;

	private Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.svrargssettings);

		handler = new IncomingHandler(this);
		
		saveBtn = (Button) findViewById(R.id.svrargssettings_btn_save);
		saveBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				StringBuffer buffer = new StringBuffer();
				buffer.append(ipAddressPart1Edit.getText().toString());
				buffer.append(SvrArgsSettingsActivity.this
						.getString(R.string.dot));
				buffer.append(ipAddressPart2Edit.getText().toString());
				buffer.append(SvrArgsSettingsActivity.this
						.getString(R.string.dot));
				buffer.append(ipAddressPart3Edit.getText().toString());
				buffer.append(SvrArgsSettingsActivity.this
						.getString(R.string.dot));
				buffer.append(ipAddressPart4Edit.getText().toString());
				String ipAddress = buffer.toString();

				int port = Integer.parseInt(portEdit.getText().toString());

				int timeout = Integer
						.parseInt(timeoutEdit.getText().toString());

				ServerSettings settings = new ServerSettings(
						SvrArgsSettingsActivity.this);
				settings.saveSettings(ipAddress, port, timeout);
				
				SvrArgsSettingsActivity.this.setResult(RESULT_ARGS_CHANGED);
				SvrArgsSettingsActivity.this.finish();
			}
		});

		cancelBtn = (Button) findViewById(R.id.svrargssettings_btn_cancel);
		cancelBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				SvrArgsSettingsActivity.this.setResult(RESULT_CANCELED);
				SvrArgsSettingsActivity.this.finish();
			}
		});
		
		ipAddressPart1Edit = (EditText) findViewById(R.id.svrargssettings_ip_address_part1);
		ipAddressPart1Edit
				.setFilters(new InputFilter[] { new InputFilter.LengthFilter(3) });
		ipAddressPart1Edit.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				saveBtn.setEnabled(false);
			}

			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				String part1 = ipAddressPart1Edit.getText().toString();
				if (part1.length() == 3) {
					int value = Integer.parseInt(part1);
					if ((value < 1) || (value > 223)) {
						Toast.makeText(
								SvrArgsSettingsActivity.this,
								MessageFormat.format(
										SvrArgsSettingsActivity.this
												.getString(R.string.ip_address_part1_err_msg),
										value), Toast.LENGTH_SHORT).show();
						if (value < 1) {
							ipAddressPart1Edit.setText("1");
						} else if (value > 223) {
							ipAddressPart1Edit.setText("223");
						}
						ipAddressPart1Edit.requestFocus();
					} else {
						ipAddressPart2Edit.requestFocus();
					}
				}
			}
		});

		ipAddressPart2Edit = (EditText) findViewById(R.id.svrargssettings_ip_address_part2);
		ipAddressPart2Edit
				.setFilters(new InputFilter[] { new InputFilter.LengthFilter(3) });
		ipAddressPart2Edit.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				saveBtn.setEnabled(false);
			}

			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				String part2 = ipAddressPart2Edit.getText().toString();
				if (part2.length() == 3) {
					int value = Integer.parseInt(part2);
					if (value > 255) {
						Toast.makeText(
								SvrArgsSettingsActivity.this,
								MessageFormat.format(
										SvrArgsSettingsActivity.this
												.getString(R.string.ip_address_part234_err_msg),
										value), Toast.LENGTH_SHORT).show();
						ipAddressPart2Edit.setText("255");
					} else {
						ipAddressPart3Edit.requestFocus();
					}
				}
			}
		});

		ipAddressPart3Edit = (EditText) findViewById(R.id.svrargssettings_ip_address_part3);
		ipAddressPart3Edit
				.setFilters(new InputFilter[] { new InputFilter.LengthFilter(3) });
		ipAddressPart3Edit.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				saveBtn.setEnabled(false);
			}

			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				String part3 = ipAddressPart3Edit.getText().toString();
				if (part3.length() == 3) {
					int value = Integer.parseInt(part3);
					if (value > 255) {
						Toast.makeText(
								SvrArgsSettingsActivity.this,
								MessageFormat.format(
										SvrArgsSettingsActivity.this
												.getString(R.string.ip_address_part234_err_msg),
										value), Toast.LENGTH_SHORT).show();
						ipAddressPart3Edit.setText("255");
					} else {
						ipAddressPart4Edit.requestFocus();
					}
				}
			}
		});

		ipAddressPart4Edit = (EditText) findViewById(R.id.svrargssettings_ip_address_part4);
		ipAddressPart4Edit
				.setFilters(new InputFilter[] { new InputFilter.LengthFilter(3) });
		ipAddressPart4Edit.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				saveBtn.setEnabled(false);
			}

			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				String part4 = ipAddressPart4Edit.getText().toString();
				if (part4.length() == 3) {
					int value = Integer.parseInt(part4);
					if (value > 255) {
						Toast.makeText(
								SvrArgsSettingsActivity.this,
								MessageFormat.format(
										SvrArgsSettingsActivity.this
												.getString(R.string.ip_address_part234_err_msg),
										value), Toast.LENGTH_SHORT).show();
						ipAddressPart4Edit.setText("255");
					}
				}
			}
		});

		portEdit = (EditText) findViewById(R.id.svrargssettings_port);
		portEdit.setFilters(new InputFilter[] { new InputFilter.LengthFilter(5) });
		portEdit.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				saveBtn.setEnabled(false);
			}

			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				String portStr = portEdit.getText().toString();
				if (portStr.length() == 5) {
					int value = Integer.parseInt(portStr);
					if (value > 65535) {
						Toast.makeText(
								SvrArgsSettingsActivity.this,
								MessageFormat.format(
										SvrArgsSettingsActivity.this
												.getString(R.string.port_not_opened),
										value), Toast.LENGTH_SHORT).show();
						portEdit.setText("65535");
					}
				}
			}
		});

		timeoutEdit = (EditText) findViewById(R.id.svrargssettings_timeout);
		timeoutEdit.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				saveBtn.setEnabled(false);
			}

			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

		ServerSettings settings = new ServerSettings(this);
		if (settings.isSet()) {
			String ipAddress = settings.getIpAddress();
			String[] parts = ipAddress.split("\\.");
			if (4 == parts.length) {
				ipAddressPart1Edit.setText(parts[0]);
				ipAddressPart2Edit.setText(parts[1]);
				ipAddressPart3Edit.setText(parts[2]);
				ipAddressPart4Edit.setText(parts[3]);
			}

			portEdit.setText(Integer.toString(settings.getPort()));

			timeoutEdit.setText(Integer.toString(settings.getTimeout()));
		}

		testBtn = (Button) findViewById(R.id.svrargssettings_btn_test);
		testBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				List<Integer> errList = checkInput();
				if (errList.size() == 0) {
					StringBuffer buffer = new StringBuffer();
					buffer.append(ipAddressPart1Edit.getText().toString());
					buffer.append(SvrArgsSettingsActivity.this
							.getString(R.string.dot));
					buffer.append(ipAddressPart2Edit.getText().toString());
					buffer.append(SvrArgsSettingsActivity.this
							.getString(R.string.dot));
					buffer.append(ipAddressPart3Edit.getText().toString());
					buffer.append(SvrArgsSettingsActivity.this
							.getString(R.string.dot));
					buffer.append(ipAddressPart4Edit.getText().toString());
					String ipAddress = buffer.toString();

					int port = Integer.parseInt(portEdit.getText().toString());

					int timeout = Integer.parseInt(timeoutEdit.getText()
							.toString());

					Thread thread = new WSTestThread(ipAddress, port, timeout);
					thread.start();

				} else {
					StringBuffer buffer = new StringBuffer();
					int i = 1;

					buffer.append(SvrArgsSettingsActivity.this
							.getString(R.string.error));
					buffer.append(SvrArgsSettingsActivity.this
							.getString(R.string.colon_sbc_case));

					if (errList.contains(R.id.svrargssettings_ip_address_part1)
							|| errList
									.contains(R.id.svrargssettings_ip_address_part2)
							|| errList
									.contains(R.id.svrargssettings_ip_address_part3)
							|| errList
									.contains(R.id.svrargssettings_ip_address_part4)) {
						buffer.append(i++);
						buffer.append(SvrArgsSettingsActivity.this
								.getString(R.string.dot));
						buffer.append(SvrArgsSettingsActivity.this
								.getString(R.string.ip_address_empty));
						buffer.append(SvrArgsSettingsActivity.this
								.getString(R.string.period_sbc_case));
					}

					if (errList.contains(R.id.svrargssettings_port)) {
						buffer.append(i++);
						buffer.append(SvrArgsSettingsActivity.this
								.getString(R.string.dot));
						buffer.append(SvrArgsSettingsActivity.this
								.getString(R.string.port_empty));
						buffer.append(SvrArgsSettingsActivity.this
								.getString(R.string.period_sbc_case));
					}

					if (errList.contains(R.id.svrargssettings_timeout)) {
						buffer.append(i++);
						buffer.append(SvrArgsSettingsActivity.this
								.getString(R.string.dot));
						buffer.append(SvrArgsSettingsActivity.this
								.getString(R.string.timeout_empty));
						buffer.append(SvrArgsSettingsActivity.this
								.getString(R.string.period_sbc_case));
					}

					Toast.makeText(SvrArgsSettingsActivity.this,
							buffer.toString(), Toast.LENGTH_SHORT).show();
				}
			}
		});
	}

	private List<Integer> checkInput() {
		List<Integer> errList = new ArrayList<Integer>();

		if (ipAddressPart1Edit.getText().length() == 0) {
			errList.add(R.id.svrargssettings_ip_address_part1);
		}
		if (ipAddressPart2Edit.getText().length() == 0) {
			errList.add(R.id.svrargssettings_ip_address_part2);
		}
		if (ipAddressPart3Edit.getText().length() == 0) {
			errList.add(R.id.svrargssettings_ip_address_part3);
		}
		if (ipAddressPart4Edit.getText().length() == 0) {
			errList.add(R.id.svrargssettings_ip_address_part4);
		}

		if (portEdit.getText().length() == 0) {
			errList.add(R.id.svrargssettings_port);
		}

		if (timeoutEdit.getText().length() == 0) {
			errList.add(R.id.svrargssettings_timeout);
		}

		return errList;
	}

	private static class IncomingHandler extends Handler {

		private WeakReference<SvrArgsSettingsActivity> reference;

		public IncomingHandler(SvrArgsSettingsActivity activity) {
			// TODO Auto-generated constructor stub
			reference = new WeakReference<SvrArgsSettingsActivity>(activity);
		}

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			SvrArgsSettingsActivity activity = reference.get();

			switch (msg.what) {
			case MESSAGE_SHOW_DIALOG:
				activity.dialog = ProgressDialog.show(activity, null,
						activity.getString(R.string.waitting));
				break;

			case MESSAGE_DISMISS_DIALOG:
				activity.dialog.dismiss();
				break;

			case MESSAGE_ENABLE_SAVE:
				activity.saveBtn.setEnabled(true);
				break;

			case MESSAGE_DISABLE_SAVE:
				activity.saveBtn.setEnabled(false);
				break;

			case MESSAGE_SHOW_TOAST:
				Toast.makeText(activity, activity.getString(msg.arg1),
						Toast.LENGTH_SHORT).show();
				break;

			default:
				break;
			}
		}
	}

	private class WSTestThread extends Thread {

		private String ipAddress;

		private int port;

		private int timeout;

		public WSTestThread(String ipAddress, int port, int timeout) {
			// TODO Auto-generated constructor stub
			this.ipAddress = ipAddress;
			this.port = port;
			this.timeout = timeout;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			// super.run();
			ServerSettings settings = new ServerSettings(
					SvrArgsSettingsActivity.this);
			handler.sendEmptyMessage(MESSAGE_SHOW_DIALOG);
			int result = settings.debug(ipAddress, port, timeout);
			Message msg = null;
			switch (result) {
			
			case ServerSettings.SUCCESS:
				handler.sendEmptyMessage(MESSAGE_ENABLE_SAVE);
				handler.sendEmptyMessage(MESSAGE_DISMISS_DIALOG);
				msg = handler.obtainMessage();
				msg.what = MESSAGE_SHOW_TOAST;
				msg.arg1 = R.string.test_success;
				handler.sendMessage(msg);
				break;

			case ServerSettings.NETWORK_NOT_AVAILABLE:
				handler.sendEmptyMessage(MESSAGE_DISABLE_SAVE);
				handler.sendEmptyMessage(MESSAGE_DISMISS_DIALOG);
				msg = handler.obtainMessage();
				msg.what = MESSAGE_SHOW_TOAST;
				msg.arg1 = R.string.network_not_connected;
				handler.sendMessage(msg);
				break;

			case ServerSettings.INVALID_IP_ADDRESS:
				handler.sendEmptyMessage(MESSAGE_DISABLE_SAVE);
				handler.sendEmptyMessage(MESSAGE_DISMISS_DIALOG);
				msg = handler.obtainMessage();
				msg.what = MESSAGE_SHOW_TOAST;
				msg.arg1 = R.string.invalid_ip_address;
				handler.sendMessage(msg);
				break;

			case ServerSettings.IP_ADDRESS_NOT_REACHABLE:
				handler.sendEmptyMessage(MESSAGE_DISABLE_SAVE);
				handler.sendEmptyMessage(MESSAGE_DISMISS_DIALOG);
				msg = handler.obtainMessage();
				msg.what = MESSAGE_SHOW_TOAST;
				msg.arg1 = R.string.ip_address_not_reachadle;
				handler.sendMessage(msg);
				break;

			case ServerSettings.PORT_NOT_OPENED:
				handler.sendEmptyMessage(MESSAGE_DISABLE_SAVE);
				handler.sendEmptyMessage(MESSAGE_DISMISS_DIALOG);
				msg = handler.obtainMessage();
				msg.what = MESSAGE_SHOW_TOAST;
				msg.arg1 = R.string.port_not_opened;
				handler.sendMessage(msg);
				break;
				
			case ServerSettings.INTERNAL_ERROR:
				handler.sendEmptyMessage(MESSAGE_DISABLE_SAVE);
				handler.sendEmptyMessage(MESSAGE_DISMISS_DIALOG);
				msg = handler.obtainMessage();
				msg.what = MESSAGE_SHOW_TOAST;
				msg.arg1 = R.string.internal_error;
				handler.sendMessage(msg);
				break;

			case ServerSettings.WEB_SERVICE_NOT_AVAILABLE:
				handler.sendEmptyMessage(MESSAGE_DISABLE_SAVE);
				handler.sendEmptyMessage(MESSAGE_DISMISS_DIALOG);
				msg = handler.obtainMessage();
				msg.what = MESSAGE_SHOW_TOAST;
				msg.arg1 = R.string.webservice_not_available;
				handler.sendMessage(msg);
				break;

			default:
				break;
			}
		}
	}
}
